/*
 * @Author: yangni 920556271@qq.com
 * @Date: 2023-11-30 16:40:49
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-01-30 16:32:49
 * @FilePath: /yt-devops/lib/pages/mine/user_manage/mine_choose_organization/mine_choose_organization_controller.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/yt_expandable_tree/model/m_stack.dart';
import 'package:yt_devops/components/yt_expandable_tree/model/tree_mode.dart';
import 'package:yt_devops/pages/mine/user_manage/user_manage_controller.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/auth/auth_services.dart';

class MineChooseOrganizationController extends GetxController {
  final _authServices = Get.put(AuthServices());
  List<TreeNode> treeData = [];
  UserManageController controller = Get.find();
  List selectedDeviceIds = [];
  String searchString = '';

  String organizationIdSting = '';
  String organizationNameSting = '';
  List allResultData = [];
  int type = 0;
  @override
  void onInit() {
    super.onInit();
    var args = Get.arguments;
    if (args != null) {
      Log.d('args===' + args.toString());
      selectedDeviceIds = args['selectedID'];
    }
    if (args['type'] != null) {
      type = args['type'];
    }

    Log.d('selectedDeviceIds===' + selectedDeviceIds.toString());
    getSiteTree();
  }

  @override
  void onReady() {}

  @override
  void onClose() {}

  ///处理搜素后的数据,本地处理
  getData() {
    getSiteTree();
  }

  getSiteTree() async {
    showLoading(toast: ResKey.loading.tr);
    List result = await _authServices
        .getUserManagerSiteTree({'type': type}, onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    var stack = MStack();

    ///后台返回数据和treeData不一致 需要自己手动处理
    for (var element in result) {
      if (element['children']?.isNotEmpty == true) {
        stack.push(element);
        while (stack.top > 0) {
          Map child = stack.pop();
          for (var item in child['children'] ?? []) {
            item['label'] = item['label'] ?? item['name'];
            item['id'] = '${child['id']}-${item['id']}';
            if (item['sites']?.isNotEmpty == true) {
              item['children'] = item['sites'];
            }
            stack.push(item);
          }
        }
      }
    }

    allResultData = result;
    treeData = getTreeData(result);
    update();
  }
  _handleResultData(List resultData) {

    var stack = MStack();
    if(resultData != null && resultData.isNotEmpty){

      ///后台返回数据和treeData不一致 需要自己手动处理
      for (var element in resultData) {
        if (element['children']?.isNotEmpty == true) {
          stack.push(element);
          while (stack.top > 0) {
            Map child = stack.pop();
            for (var item in child['children'] ?? []) {
              item['label'] = item['label'] ?? item['name'];
              item['id'] = '${child['id']}-${item['id']}';
              if (item['sites']?.isNotEmpty == true) {
                item['children'] = item['sites'];
              }
              stack.push(item);
            }
          }
        }
      }
      treeData = getTreeData(resultData);
      update();
    }else{
      treeData = [];
      update();
    }

  }

  List<TreeNode> getTreeData(List data) => treeData = TreeNode.listFrom(
      source: data,
      value: (index, item) => item['id'].toString(),
      title: (index, item) => item['label'],
      subNodes: (index, item) => getTreeData(item['children'] ?? []));
  void confirm() {
    Log.d('selectedDeviceIds==' + selectedDeviceIds.toString());
    controller.getOrganizationId(organizationIdSting);
    Get.back();
  }

  searchData(String keyword) {
    if (keyword != null && keyword.isEmpty) {
      _handleResultData(allResultData);
    } else {
      if (allResultData != null && allResultData.isNotEmpty) {
        List list = searchLabel(allResultData, keyword);
        _handleResultData(list);
      }
    }
  }

  List<Map<String, dynamic>> searchLabel(List<dynamic> nodes, String keyword) {
    List<Map<String, dynamic>> result = [];
    for (var node in nodes) {
      Map<String, dynamic>? newNode = searchNode(node, keyword);
      if (newNode != null) {
        result.add(newNode);
      }
    }
    return result;
  }

  Map<String, dynamic>? searchNode(Map<String, dynamic> node, String keyword) {
    bool matchFound = node['label'].contains(keyword);
    List<Map<String, dynamic>> newChildren = [];

    if (node.containsKey('children')) {
      for (var child in node['children']) {
        Map<String, dynamic>? newChild = searchNode(child, keyword);
        if (newChild != null) {
          newChildren.add(newChild);
          matchFound = true;
        }
      }
    }

    if (matchFound) {
      Map<String, dynamic> newNode = Map<String, dynamic>.from(node);
      if (newChildren.isNotEmpty) {
        newNode['children'] = newChildren;
      }
      return newNode;
    } else {
      return null;
    }
  }

}
